package com.springBoot.fileService.util;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @Copyright: Shanghai Definesys Company.All rights reserved.
 * @Description:
 * @author: chuhaitao
 * @since: 2018/12/4 10:29
 * @history: 1.2018/12/4 created by chuhaitao
 */
public class FileUtil {


    /**
     * 生成文件的存储名称
     *
     * @param file
     * @return
     */
    public static String getFileUUIDName(MultipartFile file) {
        String extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        return UUID.randomUUID().toString() + extName;
    }


    /**
     * 文件上传的存储路径
     *
     * @param uploadFilePathPre
     * @return
     */
    public static String getUploadFilePath(String uploadFilePathPre) {
        String uploadFilePath = uploadFilePathPre + "/" + new SimpleDateFormat("yyyyMM").format(new Date());
        return uploadFilePath;
    }

    /**
     * 文件的下载
     *
     * @param httpServletResponse
     * @param file
     */
    public static void download(HttpServletResponse httpServletResponse, File file, String newFileName) {
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            byte[] buffer = new byte[1024];
            httpServletResponse.setContentType("application/force-download");
            httpServletResponse.setCharacterEncoding("utf-8");
            // 设置下载不打开、文件名、和编码，不然打不出名称
            httpServletResponse.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(newFileName, "utf-8"));
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            OutputStream os = httpServletResponse.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
